package org.bigdata.framework.core.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
public class TreeJsion {

	 private static List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();;
	 static{
	  LinkedHashMap<String, Object> mp = null;
	  mp = new LinkedHashMap<String, Object>();
	  mp.put("id", 1);
	  mp.put("name", "123");
	   mp.put("pId", 0);
		r.add(mp);
		 mp= new LinkedHashMap<String, Object>();
		 mp.put("id", 2);
		 mp.put("name", "123");
		 mp.put("pId", 1);
		 r.add(mp);
		 mp= new LinkedHashMap<String, Object>();
		 mp.put("id", 3);
		 mp.put("name", "123");
		 mp.put("pId", 1);
		 r.add(mp);
		 mp= new LinkedHashMap<String, Object>();
		 mp.put("id", 3);
		 mp.put("name", "123");
		 mp.put("pId", 1);
		 r.add(mp);
	 }
	 
	 public static void main(String[] args) {
	  
	  StringBuffer sb = new StringBuffer();
	  LinkedHashMap<String, Object> mp = null;
	  mp = new LinkedHashMap<String, Object>();
	  mp.put("id", 1);
	   mp.put("name", "123");
	   mp.put("pId", 0);
	   System.out.println(mp.get("id"));
	  findChilds(r,sb,mp);
	  sb.deleteCharAt(sb.length()-1);
	  System.out.println(TreeJsion.get(mp, r));
	 }
	 public static String get(LinkedHashMap<String, Object> mp,List<HashMap<String, Object>> rr)
	 {
		  StringBuffer sb = new StringBuffer();
		  findChilds(rr,sb,mp);
		  sb.deleteCharAt(sb.length()-1);
		 return sb.toString();
	 }
	 private static void findChilds(List<HashMap<String, Object>> r,StringBuffer sb,HashMap<String, Object> person){
		
	  sb.append("{\"id\":\""+person.get("id")+"\""+",\"ld\":\""+person.get("url")+"\""+",\"icon\":\""+person.get("icon")+"\""+",\"name\":\""+person.get("name")+"\"");
	  List<HashMap<String, Object>> temps = getChilds(r,person);
	  if(temps.size()>0){
	   sb.append(",\"child\":[");
	   for(HashMap<String, Object> ds : temps){       
	    findChilds(r,sb,ds);
	   }
	   sb.deleteCharAt(sb.length()-1);
	   sb.append("]");
	  }
	  sb.append("},");
	 }
	 private static List<HashMap<String, Object>> getChilds(List<HashMap<String, Object>> r,HashMap<String, Object> person){
		 List<HashMap<String, Object>> per= new ArrayList<HashMap<String, Object>>();
	  for(HashMap<String, Object> p : r){
	   if(person.get("id").equals(p.get("pId"))){
	    per.add(p);
	   }
	  }
	  return per;
	 }
	
}
